package com.tunan.system.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tunan.common.PagePermissionUtil;
import com.tunan.common.Result;
import com.tunan.common.resultSub.ResultFailure;
import com.tunan.common.resultSub.ResultSuccess;
import com.tunan.persistence.model.TSysMenu;
import com.tunan.system.service.IdentifierGenerator;
import com.tunan.system.service.SysMenuService;

@Controller
@RequestMapping(value = "SysMenu")
public class SysMenuController extends BaseController {
	@Autowired
	private SysMenuService sysMenuService;
	
	@Autowired
	private IdentifierGenerator identifierGenerator;
	
	private Logger log = Logger.getLogger(SysMenuController.class);

	@RequestMapping(value = "addMenu", method = RequestMethod.GET)
	@ResponseBody
	public TSysMenu addMenu(String id, HttpServletRequest request) {
		if (StringUtils.isNotBlank(id)) {
			return sysMenuService.selectOne(id);
		}
		return  null;
	}

	@RequestMapping(value = "sysMenuList", method = RequestMethod.GET)
	public ModelAndView sysMenuList(String menuId, HttpServletRequest request) {
		if(StringUtils.isNotBlank(menuId)){
			request.setAttribute("pagePermission", PagePermissionUtil.getPRight(menuId, request.getSession()));
		}
		return new ModelAndView("/system/sysMenuList");
	}

	/**
	 * 查询用户
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "queryAll", method = RequestMethod.GET)
	@ResponseBody
	public List list() {
		List<Map<String,Object>> lists = new ArrayList<Map<String,Object>>();
		try {
			List<TSysMenu> parentMenuList = sysMenuService.findByParentMenu("0");
			for (TSysMenu menu : parentMenuList) {
				Map<String,Object> maps = new HashMap<String,Object>();
				maps.put("id", menu.getId());
				maps.put("text", menu.getName());
				maps.put("children", loadMenusByParentId(menu.getId()));
				lists.add(maps);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lists;
	}

	/**
	 * 通过一级菜单ID获得其对应的所有子菜单列表
	 * @param parentId
	 * @retur
	 * List
	 */
	@SuppressWarnings("rawtypes")
	private List loadMenusByParentId(String parentId) {
		List lists = new ArrayList();
		List<Map<String,Object>> l = new ArrayList<Map<String,Object>>();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("parentMenu", parentId);
		Map<String,Object> maps = null;
		try {
			List<TSysMenu> list = sysMenuService.findByParentMenu(parentId);
			for (TSysMenu menu : list)  {
				maps = new HashMap<String,Object>();
				lists = loadMenusByParentId(menu.getId());
				if (lists.size() > 0) {
					maps.put("id", menu.getId());
					maps.put("text", menu.getName());
					maps.put("state", "close");
				}
				maps.put("id", menu.getId());
				maps.put("text", menu.getName());
				maps.put("state", "close");
				if (lists.size() > 0) {
					maps.put("children", lists);
				}
				l.add(maps);
			}

		} catch (Exception e) {
			log.error(e);
		}
		return l;
	}
	
	/**
	 * 获取第一级菜单
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "loadParentMenu", method = RequestMethod.GET)
	@ResponseBody
	public List loadParentMenu() {
		List<Map<String,Object>> lists = new ArrayList<Map<String,Object>>();
		try {
			List<TSysMenu> list = sysMenuService.findByParentMenu("0");
			for (TSysMenu menu : list) {
				Map<String,Object> maps = new HashMap<String,Object>();
				maps.put("id", menu.getId());
				maps.put("text", menu.getName());
				lists.add(maps);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return lists;
	}
	
	/**
	 * 新增和修改
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public Result save(@ModelAttribute("menu") TSysMenu menu) {
		ResultSuccess rs = new ResultSuccess();
		ResultFailure rf = new ResultFailure();
		try {
			if (menu != null) {
				if(StringUtils.isBlank(menu.getParentMenu())){
					menu.setParentMenu("0");
				}
				if (StringUtils.isNotBlank(menu.getId())) {
					sysMenuService.update(menu);
					rs.setMessage("修改成功");
				} else {
					menu.setId(identifierGenerator.generate());
					sysMenuService.insertSelective(menu);
					rs.setMessage("新增成功");
				}

			}
			return rs;

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		rf.setMessage("操作失败");
		return rf;
	}
	
	@RequestMapping(value = "selectMenuIcon", method = RequestMethod.GET)
	public ModelAndView selectMenuIcon() {
		return new ModelAndView("/system/sysMenuIconSelect");
	}
	
	/**
	 * 删除
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public Result delete(String id) {
		ResultSuccess rs = new ResultSuccess();
		ResultFailure rf = new ResultFailure();
		try {
			if (StringUtils.isNotBlank(id)) {
				sysMenuService.delete(id);
			}
			rs.setMessage("删除成功");
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		rf.setMessage("删除失败");
		return rf;
	}

	/**
	 * 批量删除
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "batchDel", method = RequestMethod.POST)
	public Result batchDel(String ids) {
		ResultSuccess rs = new ResultSuccess();
		ResultFailure rf = new ResultFailure();
		try {
			if (StringUtils.isNotBlank(ids)) {
				List<String> idList = new ArrayList<String>();
				if (ids.contains(",")) {
					idList = Arrays.asList(ids.split(","));
				} else {
					idList.add(ids);
				}
				sysMenuService.batchDel(idList);
			}
			rs.setMessage("批量删除成功");
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		rf.setMessage("批量删除失败");
		return rf;
	}

}
